package com.huangkailong.sqlprinter.core;

import com.sun.tools.attach.VirtualMachine;
import org.apache.commons.cli.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author huangkailong
 * @since 1.0.0
 */
public class SqlPrinterCoreMain {
    public static void main(String[] args) {
        try {
            CommandLine commandLine = parseCliArgs(args);
            String pidStr = commandLine.getOptionValue("pid");
            String agentPath = commandLine.getOptionValue("agent");
            checkArgs(pidStr, agentPath);
            loadAgentToProcess(pidStr, agentPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void loadAgentToProcess(String pidStr, String agentPath) throws Exception {
        VirtualMachine virtualMachine = VirtualMachine.attach(pidStr);
        virtualMachine.loadAgent(agentPath);
        virtualMachine.detach();
    }

    private static String encodeArg(String arg) {
        try {
            return URLEncoder.encode(arg, "GBK");
        } catch (UnsupportedEncodingException e) {
            return arg;
        }
    }

    private static CommandLine parseCliArgs(String[] args) throws ParseException {
        CommandLineParser parser = new DefaultParser();
        Options options = new Options();
        options.addOption("pid",  "pid", true, "attach process pid");
        options.addOption("agent","agent", true, "java agent jar path");
        return parser.parse(options, args);
    }

    private static void checkArgs(String pidStr, String agentPath) {
        if(pidStr == null || pidStr.length() == 0){
            System.out.println("请传入 pid!");
            System.exit(-1);
        }

        long pid = 0;
        try {
            pid = Long.parseLong(pidStr);
        } catch (NumberFormatException e) {
            System.out.println("pid 必须是整数!");
            System.exit(-1);
        }
        if(pid < 0){
            System.out.println("无效的 pid!");
            System.exit(-1);
        }

        if(agentPath == null || agentPath.length() == 0){
            System.out.println("请传入 agent!");
            System.exit(-1);
        }
    }
}
